package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.utils.MediaUtil;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;
import com.shoujifeng.snowmusic.player.utils.ViewHolder;

/**
 * 
 * 添加歌曲到歌单
 * 
 * @author luo
 * 
 */

public class AddToMenuActivity extends Activity {
	private ListView contactsDelList;
	private Button addMenuBtn;
	private List<Mp3Info> mp3Infos;
	private MusicPlayer musicPlayer;
	private MyAdapter adapter;
	private ArrayList<String> listStr = null;
	private List<HashMap<String, String>> mp3list = null;
	private View lineLay;
	private Button selectAllBtn;
	private boolean selectAll = false;
	private RelativeLayout headView;
	private TextView headText;
	private ImageButton breakBtn;
	private ProgressDialog pd;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_to_menu_layout);
		init();

	}

	private void init() {
		contactsDelList = (ListView) findViewById(R.id.contacts_delete_list);
		contactsDelList.setDivider(null);
		lineLay = LayoutInflater.from(AddToMenuActivity.this).inflate(
				R.layout.line_layout, null);
		contactsDelList.addFooterView(lineLay);
		addMenuBtn = (Button) findViewById(R.id.add_menu_btn);
		selectAllBtn = (Button) findViewById(R.id.select_all_btn);
		headView = (RelativeLayout) findViewById(R.id.headLay);
		headText = (TextView) headView.findViewById(R.id.head_text);
		headText.setText("添加单曲");
		breakBtn = (ImageButton) headView.findViewById(R.id.breakBtn);

		showCheckBoxListView();
		selectAllBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (selectAll == false) {
					selectAll = true;
					selectAllBtn
							.setBackgroundResource(R.drawable.select_all_yes_bg);
				} else {
					selectAll = false;
					selectAllBtn
							.setBackgroundResource(R.drawable.select_all_bgl);
				}

				for (int i = 0; i < mp3Infos.size(); i++) {
					if (MyAdapter.isSelected.get(i) == false) {
						MyAdapter.isSelected.put(i, true);
						listStr.add(mp3Infos.get(i).getTitle());
						MyAdapter.noList.add(i + "");
					} else {
						MyAdapter.isSelected.put(i, false);
						listStr.remove(mp3Infos.get(i).getTitle());
						MyAdapter.noList.remove(i + "");
					}
				}

				adapter.notifyDataSetChanged();
			}
		});

		addMenuBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pd = ProgressDialog.show(AddToMenuActivity.this, null,
						"请稍后.....", true);

				for (int i = 0; i < MyAdapter.noList.size(); i++) {
					System.out.println(mp3list.get(
							Integer.valueOf(MyAdapter.noList.get(i))).get(
							"title"));
					DatabaseUtil databaseUtil = new DatabaseUtil(
							AddToMenuActivity.this);

					String name = getIntent().getExtras().getString("name");
					String musicName = mp3list.get(
							Integer.valueOf(MyAdapter.noList.get(i))).get(
							"title");
					String playerName = mp3list.get(
							Integer.valueOf(MyAdapter.noList.get(i))).get(
							"Artist");
					long duration = Integer.parseInt(mp3list.get(
							Integer.valueOf(MyAdapter.noList.get(i))).get(
							"duration"));
					long size = Integer.parseInt(mp3list.get(
							Integer.valueOf(MyAdapter.noList.get(i))).get(
							"size"));
					String url = mp3list.get(
							Integer.valueOf(MyAdapter.noList.get(i)))
							.get("url");
					databaseUtil.insertMenu(name, musicName, playerName,
							duration, size, url);

				}
				pd.dismiss();
				Toast.makeText(AddToMenuActivity.this, " 添加成功",
						Toast.LENGTH_SHORT).show();
				if (NativeMusicManageActivity.activityName
						.equals("MusicMenuContentActivity")) {
					String name = getIntent().getExtras().getString("name");
					Intent intent = new Intent(AddToMenuActivity.this,
							MusicMenuContentActivity.class);
					intent.putExtra("name", name);
					startActivity(intent);
				} else {
					String name = getIntent().getExtras().getString("name");
					Intent intent = new Intent(AddToMenuActivity.this,
							MyTabHost.class);
					intent.putExtra("name", name);
					startActivity(intent);
				}
			}

		});

		breakBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	// 显示带有checkbox的listview
	public void showCheckBoxListView() {
		MediaUtil mediaUtil = new MediaUtil();
		mp3Infos = mediaUtil.getMp3Infos(AddToMenuActivity.this);
		mp3list = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < mp3Infos.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("album", mp3Infos.get(i).getAlbum());
			map.put("Artist", mp3Infos.get(i).getArtist());
			map.put("title", mp3Infos.get(i).getTitle());
			map.put("url", mp3Infos.get(i).getUrl());
			map.put("duration", mp3Infos.get(i).getDuration() + "");
			map.put("size", mp3Infos.get(i).getSize() + "");
			mp3list.add(map);
		}
		MusicPlayer.musicInfos = mp3Infos;
		adapter = new MyAdapter(this, mp3list, R.layout.add_to_menu_list,
				new String[] { "title", "Artist" }, new int[] { R.id.musicname,
						R.id.playername });
		contactsDelList.setAdapter(adapter);

		listStr = new ArrayList<String>();
		MyAdapter.noList = new ArrayList<String>();
		contactsDelList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				ViewHolder holder = (ViewHolder) view.getTag();
				holder.checkBox.toggle();// 在每次获取点击的item时改变checkbox的状态
				MyAdapter.isSelected.put(position, holder.checkBox.isChecked()); // 同时修改map的值保存状态
				if (holder.checkBox.isChecked() == true) {
					listStr.add(mp3list.get(position).get("title"));
					MyAdapter.noList.add(position + "");
				} else {
					listStr.remove(mp3list.get(position).get("title"));
					MyAdapter.noList.remove(position + "");
				}
			}

		});
	}

	// 为listview自定义适配器内部类
	public static class MyAdapter extends BaseAdapter {
		public static HashMap<Integer, Boolean> isSelected;
		private static List<String> noList;
		private Context context = null;
		private LayoutInflater inflater = null;
		private List<HashMap<String, String>> list = null;
		private String keyString[] = null;
		private String itemString = null; // 记录每个item中textview的值
		private int idValue[] = null;// id值

		public MyAdapter(Context context, List<HashMap<String, String>> list,
				int resource, String[] from, int[] to) {
			this.context = context;
			this.list = list;
			keyString = new String[from.length];
			idValue = new int[to.length];
			System.arraycopy(from, 0, keyString, 0, from.length);
			System.arraycopy(to, 0, idValue, 0, to.length);
			inflater = LayoutInflater.from(context);
			init();
		}

		// 初始化 设置所有checkbox都为未选择
		public void init() {
			isSelected = new HashMap<Integer, Boolean>();
			noList = new ArrayList<String>();
			for (int i = 0; i < list.size(); i++) {
				isSelected.put(i, false);
			}
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			ViewHolder holder = null;
			if (holder == null) {
				holder = new ViewHolder();
				if (view == null) {
					view = inflater.inflate(R.layout.add_to_menu_list, null);
				}
				holder.musicnameView = (TextView) view
						.findViewById(R.id.musicname);
				holder.playernameView = (TextView) view
						.findViewById(R.id.playername);
				holder.checkBox = (CheckBox) view
						.findViewById(R.id.delete_list_item);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			HashMap<String, String> map = list.get(position);
			if (map != null) {
				itemString = (String) map.get(keyString[0]);
				holder.musicnameView.setText(itemString);
				holder.playernameView.setText(list.get(position).get("Artist"));
			}
			holder.checkBox.setChecked(isSelected.get(position));
			return view;
		}
	}

}
